from django.core.management.base import BaseCommand
from openpolitics.feedreader.models import *
from datetime import datetime, timedelta
from django.db.models import Q

class Command(BaseCommand):
    
    help = 'Runs a daemon to execute periodically scheduled tasks.'
    args = ''
    
    requires_model_validation = False
    
    def handle(self, *args, **options):
        force=True
        # now + 5 minutes - safe margin
        fivemin = timedelta(minutes=5)
        # one hour
        hour = timedelta(hours=1)
        now = datetime.now()
        # get all sources that were not run in last hour
        if force is True:
            sos = Source.objects.all()
        else:
            sos = Source.objects.filter(Q(last__timestamp__lte=now-hour)|
                                        Q(last=None))
        for so in sos:
            # if no last log, run
            if so.last is None:
                self.run(so)
            elif force is True:
                so.last.delete()
                self.run(so)
                
            delta = now-so.last.timestamp
            if delta >= timedelta(hours=so.interval):
                self.run(so)
        return True

    def run(self, so):
        log = Log(timestamp=datetime.now(),
                  time=None,
                  source = so,
                  status=0, #standby
                  )
        log.save()
        so.last = log
        so.status=1
        so.save()
        i=__import__('openpolitics.feedreader.readers.%s' % so.name,globals(),locals(),['reader'])
        running = True
        bufobj = None
        log.status=1
        log.save()
        print 'runned for %s' % so.name
        while running:
            chunk = Chunk(time=datetime.now(),
                          log=log,
                          url=so.site,
                          size=so.elements,
                          status=1)
            chunk.save()
            (elems, bufobj) = i.reader.reload(chunk=so.elements,
                                              start=log.items,
                                              bufobj=bufobj)
            chunk.status=2
            chunk.save()
            if elems == 0:
                log.status=2
                # set time
                delta = datetime.now()-log.timestamp
                log.time = delta.days*86400+delta.seconds
                log.save()
                log.chunks.all().delete()
                so.status=0
                so.save()
                print 'finished %s' % elems
                return True
            else:
                log.items+=elems
                log.save()
                print 'loaded %s' % elems
        
        
